package com.bobo.gmall.realtime.utils;

import com.alibaba.fastjson.JSONObject;
import com.bobo.gmall.realtime.common.GmallConfig;
import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JdbcUtil {

    /**
     * select * from t1;
     * xxx,xxx,xxx
     * xxx,xxx,xxx
     */
    public static <T> List<T> queryList(Connection connection, String querySql, Class<T> clz,
                                        boolean underScoreToCamel) throws Exception {

        ArrayList<T> resultList = new ArrayList<>();

        PreparedStatement preparedStatement = connection.prepareStatement(querySql);
        ResultSet resultSet = preparedStatement.executeQuery();

        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();
        while (resultSet.next()){

            T t = clz.newInstance();  // 创建 泛型对象

            for (int i = 1; i < columnCount+1; i++) {
                String columnName = metaData.getColumnName(i);

                // 是否转驼峰命名
                if (underScoreToCamel){
                    columnName = CaseFormat.LOWER_UNDERSCORE
                            .to(CaseFormat.LOWER_CAMEL, columnName.toLowerCase());
                }

                // 给泛型对象赋值
                Object value = resultSet.getObject(i);
                BeanUtils.setProperty(t, columnName, value);

            }

            resultList.add(t);
        }

        preparedStatement.close();
        resultSet.close();

        return resultList;
    }


    public static void main(String[] args) throws Exception {
        Class.forName(GmallConfig.MYSQL_DRIVER);
        Connection connection = DriverManager.getConnection(GmallConfig.MYSQL_SERVER);

        List<JSONObject> queryList = queryList(connection,
                "select * from gmall_flink.base_region",
                JSONObject.class, true);
        for (JSONObject jsonObject : queryList) {
            System.out.println(jsonObject.toString());
        }
        connection.close();

    }

}
